(function() {
    //游戏构造函数
    function Game(map) {
        //添加食物、蛇和地图属性
        this.food = new Food();
        this.snake = new Snake();
        this.map = map;
    }

    //游戏开始方法
    Game.prototype.start = function() {
        this.food.render(this.map);
        this.snake.render(this.map);

        // this.snake.move();
        // this.snake.remove(this.map);
        // this.snake.render(this.map);
        bindKey.call(this);
        runSnake.call(this);
    }

    //监听上下左右按键改变运动方向
    function bindKey() {
        document.onkeydown = e => {
            switch(e.keyCode) {
                case 37:
                    this.snake.direction = 'left';
                    break;
                case 38:
                    this.snake.direction = 'top';
                    break;
                case 39:
                    this.snake.direction = 'right';
                    break;
                case 40:
                    this.snake.direction = 'bottom';
                    break;
            }
        }
    }

    //蛇运动
    function runSnake() {
        var timer = setInterval(() => {
            this.snake.move();
            this.snake.remove(this.map);
            this.snake.render(this.map);

            //边界碰撞检测
            var maxX = this.map.offsetWidth / this.snake.width;
            var maxY = this.map.offsetHeight / this.snake.height;

            var headX = this.snake.body[0].x;
            var headY = this.snake.body[0].y;

            //食物碰撞检测
            var foodX = this.food.x;
            var foodY = this.food.y;

            var hX = headX * this.snake.width;
            var hY = headY * this.snake.height;

            if (foodX === hX && foodY === hY) {
                this.food.remove(this.map, 0);
                //新生成食物
                this.food.render(this.map);

                var last = this.snake.body[this.snake.body.length - 1];
                this.snake.body.push({
                    x: last.x,
                    y: last.y,
                    color: last.color
                })
            }

            if (headX < 0 || headX >= maxX || headY < 0 || headY >= maxY) {
                clearInterval(timer);
            }
        }, 150);
    }

    //向外暴露Game
    window.Game = Game;
})();
